import { login, getUserInfo } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
  },
  SET_USER_INFO(state, userInfo) {
    console.log('Store SET_USER_INFO - userInfo:', userInfo)
    console.log('Store SET_USER_INFO - role:', userInfo.role)
    state.userInfo = userInfo
  },
  UPDATE_USER_INFO(state, userInfo) {
    console.log('Store UPDATE_USER_INFO - userInfo:', userInfo)
    console.log('Store UPDATE_USER_INFO - role:', userInfo.role)
    state.userInfo = { ...state.userInfo, ...userInfo }
  },
  CLEAR_USER_INFO(state) {
    state.token = ''
    state.userInfo = {}
    removeToken()
    localStorage.removeItem('userInfo')
  }
}

const actions = {
  // 登录
  async login({ commit }, loginData) {
    try {
      // 如果传入的是完整的登录响应数据
      if (loginData.token && loginData.user) {
        const { token, user } = loginData
        
        // 确保ID作为字符串处理
        const userInfo = {
          ...user,
          id: String(user.id) // 强制转换为字符串
        }
        
        // 保存token和用户信息
        setToken(token)
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        
        commit('SET_TOKEN', token)
        commit('SET_USER_INFO', userInfo)
        
        return { code: 200, message: '登录成功' }
      } else {
        // 原有的API调用方式（保留兼容性）
        const response = await login(loginData)
        const { token, user } = response.data
        
        // 确保ID作为字符串处理
        const userInfo = {
          ...user,
          id: String(user.id) // 强制转换为字符串
        }
        
        // 保存token和用户信息
        setToken(token)
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
        
        commit('SET_TOKEN', token)
        commit('SET_USER_INFO', userInfo)
        
        return response
      }
    } catch (error) {
      console.error('Login error:', error)
      throw error
    }
  },

  // 获取用户信息
  async getUserInfo({ commit }) {
    try {
      const response = await getUserInfo()
      const user = response.data
      
      // 确保ID作为字符串处理
      const userInfo = {
        ...user,
        id: String(user.id) // 强制转换为字符串
      }
      
      commit('SET_USER_INFO', userInfo)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      
      return userInfo
    } catch (error) {
      console.error('Get user info error:', error)
      throw error
    }
  },

  // 刷新用户信息
  async refreshUserInfo({ commit, state }) {
    // 如果没有token，直接返回null，不抛出错误
    if (!state.token) {
      return null
    }
    
    try {
      const response = await getUserInfo()
      const user = response.data
      
      // 确保ID作为字符串处理
      const userInfo = {
        ...user,
        id: String(user.id) // 强制转换为字符串
      }
      
      commit('SET_USER_INFO', userInfo)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      
      return userInfo
    } catch (error) {
      console.error('Refresh user info error:', error)
      // 如果刷新失败，尝试从localStorage恢复
      const storedUserInfo = localStorage.getItem('userInfo')
      if (storedUserInfo) {
        try {
          const userInfo = JSON.parse(storedUserInfo)
          commit('SET_USER_INFO', userInfo)
          return userInfo
        } catch (e) {
          console.error('Failed to parse stored user info:', e)
        }
      }
      throw error
    }
  },

  // 登出
  logout({ commit }) {
    commit('CLEAR_USER_INFO')
  },

  // 重置token
  resetToken({ commit }) {
    commit('CLEAR_USER_INFO')
  }
}

const getters = {
  token: state => state.token,
  userInfo: state => state.userInfo,
  isLoggedIn: state => !!state.token,
  role: state => state.userInfo.role || '',
  permissions: state => state.userInfo.permissions || []
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 